package com.hongxun.budget.utils;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hongxun.interfaces.NovaCallback;

import dmax.dialog.SpotsDialog;

/**
 * 定位工具类，目前只需要new出来就可以回调了，只定位一次
 */

public class LocationUtils {

    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    private NovaCallback c;
    SpotsDialog spotsDialog;

    /**
     * @param context
     * @param applicationContext
     * @param locationMode       定位方式:0,高精度定位模式(GPS+网络).1:低功耗定位模式.2,仅用设备定位模式.3,默认定位（先判断网络是否可用，如果可用则使用高精度定位否则使用GPS定位）
     * @param locationType       定位模式 0-只定位一次。1，连续定位间隔3秒。
     * @param c
     */
    public LocationUtils(Context context, Context applicationContext, int locationMode, int locationType, NovaCallback c) {
        this.c = c;
        spotsDialog = new SpotsDialog(context, "正在定位...");
        spotsDialog.show();
        startLocation(applicationContext, locationMode, locationType);
    }

    private void startLocation(Context context, int locationMode, int locationType) {
        //初始化定位
        mLocationClient = new AMapLocationClient(context);
        //设置定位回调监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        AMapLocationClientOption option = new AMapLocationClientOption();
        if (locationMode == 3) {
            if (NetUtils.isConnected(context) || NetUtils.isWifi(context)) {
                locationMode = 0;
            } else {
                locationMode = 2;
            }
        }
        switch (locationMode) {
            case 0:
                option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                break;
            case 1:
                option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
                break;
            case 2:
                option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
                break;
        }
        switch (locationType) {
            case 0:
                option.setOnceLocation(true);//只获取一次定位结果
                option.setOnceLocationLatest(true);
                break;
            case 1:
                option.setInterval(3000);//连续定位间隔3秒
                break;
        }

        option.setNeedAddress(false);//设置是否返回地址信息（默认返回地址信息）

        mLocationClient.setLocationOption(option);
        //启动定位
        mLocationClient.stopLocation();
        mLocationClient.startLocation();
    }

    //异步获取定位结果
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (spotsDialog != null) {
                spotsDialog.dismiss();
                spotsDialog.cancel();
            }
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("latitude", amapLocation.getLatitude());
                    jsonObject.put("longitude", amapLocation.getLongitude());
                    jsonObject.put("address", amapLocation.getAddress());
                    jsonObject.put("altitude", amapLocation.getAltitude());
                    jsonObject.put("description", amapLocation.getDescription());
                    //解析定位结果
                    c.success(999, jsonObject);
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    c.err(999, -1, "定位失败，请重新进入界面。");
                    mLocationClient.stopLocation();
                }
            }
        }
    };

    public void stopLocation() {
        if (mLocationClient != null)
            mLocationClient.stopLocation();

    }

    public void destroy() {
        if (mLocationClient != null) {
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
            mLocationClient = null;
        }
    }

}
